package com.base.controller;

import com.base.comm.CommUrls;
import com.base.po.voip.CarPark;
import com.base.po.voip.Users;
import com.base.service.CarParkService;
import com.base.service.UsersService;
import com.base.utils.Page;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 挪车
 *
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/admin")
public class index_CarPark {
	@Autowired
	private UsersService usersService;
	@Autowired
	private CarParkService carParkService;

	// 挪车首页
	@RequestMapping("/carPark")
	public ModelAndView index(HttpServletRequest request) throws Exception {
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		Page page = new Page();
		Users users = usersService.selectByPrimaryKey(adminUserId);

		List<CarPark> carPark = null;
		page.setCurrentPageNo(1);
		if(users.getRole() < 2) {
			page.setRecordTotal(carParkService.countByAll(adminUserId));
			carPark = carParkService.selectByAll(page, adminUserId);
		}

		request.setAttribute("totlenum", page.getRecordTotal()); // 分页
		request.setAttribute("curPage", page.getCurrentPageNo());// 当前页面传入session中
		request.setAttribute("carPark", carPark);
		request.setAttribute("adminUsergrade", adminUsergrade);

		// 设置页面进行跳转
		modelAndView.setViewName("jsp/index_CarPark");
		return modelAndView;
	}

	@RequestMapping("/selectCarPark")
	public ModelAndView selectCarParkOrder(HttpServletRequest request, Integer curPage) throws Exception {
		// 设置session缓存
		if (curPage == null) {
			if (request.getSession().getAttribute("curPage") != null) {
				curPage = (Integer) request.getSession().getAttribute("curPage");
			} else {
				curPage = 1;
			}
		}
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");

		ModelAndView modelAndView = new ModelAndView();
		Page page = new Page();
        Users users = usersService.selectByPrimaryKey(adminUserId);

        List<CarPark> carPark = null;
        page.setCurrentPageNo(curPage);
		if(users.getRole() < 2) {
			page.setRecordTotal(carParkService.countByAll(adminUserId));
			carPark = carParkService.selectByAll(page, adminUserId);
		}

		request.setAttribute("totlenum", page.getRecordTotal()); // 分页
		request.setAttribute("curPage", page.getCurrentPageNo());// 当前页面传入session中

		// 设置页面进行跳转
		modelAndView.setViewName("jsp/index_CarPark");
		request.setAttribute("carPark", carPark);
		request.setAttribute("adminUsergrade", adminUsergrade);
		return modelAndView;
	}

	// 导出二维码图片
	@RequestMapping(value = "/exportNewCarPack", method = {RequestMethod.POST, RequestMethod.GET})
	public void  exportNewCarPack(HttpServletRequest request, HttpServletResponse response, String dayTime) throws Exception {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		String adminUserId = (String) request.getSession().getAttribute("adminUserId");

		// 域名
		String basePath = request.getServerName() + ":" + request.getServerPort()+ "/";
		// 服务器域名协议
		String headPath = null;
		switch (request.getScheme()) {
			case "http" :
				headPath = "1";
				break;
			case "https" :
				headPath = "2";
				break;
			default:
				headPath = "3";
		}

		String sourceFilePath = CommUrls.FILEPATH + "CarPackQRCode/" + adminUserId + "_" + dayTime;
		String zipFilePath = CommUrls.FILEPATH + "/Zip";
		boolean flag = false;
		File sourceFile = new File(sourceFilePath);
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		ZipOutputStream zos = null;

		if(sourceFile.exists() == false){
			System.out.println("待压缩的文件目录："+sourceFilePath+"不存在.");
			sourceFile.mkdir(); // 新建目录
		}
		try {
			File zipFile = new File(zipFilePath + "/" + adminUserId + "_" + dayTime +".zip");
			if(zipFile.exists()){
				System.out.println(zipFilePath + "目录下存在名字为:" + adminUserId + "_" + dayTime + ".zip" +"打包文件.");
			}else{
				File[] sourceFiles = sourceFile.listFiles();
				if(null == sourceFiles || sourceFiles.length<1){
					System.out.println("待压缩的文件目录：" + sourceFilePath + "里面不存在文件，无需压缩.");
					headPath = "3";
				}else{
					fos = new FileOutputStream(zipFile);
					zos = new ZipOutputStream(new BufferedOutputStream(fos));
					byte[] bufs = new byte[1024*10];
					for(int i=0;i<sourceFiles.length;i++){
						//创建ZIP实体，并添加进压缩包
						ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
						zos.putNextEntry(zipEntry);
						//读取待压缩的文件并写进压缩包里
						fis = new FileInputStream(sourceFiles[i]);
						bis = new BufferedInputStream(fis, 1024*10);
						int read = 0;
						while((read=bis.read(bufs, 0, 1024*10)) != -1){
							zos.write(bufs,0,read);
						}
					}
					flag = true;
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally{
			//关闭流
			try {
				if(null != bis) bis.close();
				if(null != zos) zos.close();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}

		// 数据库下载路径
		String fileName = basePath + "file/Zip/" + adminUserId + "_" + dayTime +".zip";

		Map<String, String> map = new HashMap<>();
		map.put("fileName", fileName);
		map.put("headPath",headPath);
		JSONObject json = JSONObject.fromObject(map);
		out.println(json);
	}
}
